package com.blockchain.securewallet.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.adapter.WordsAdapter;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.btc.BTCUtils;
import com.blockchain.securewallet.btc.Transaction;
import com.blockchain.securewallet.btc.UnspentOutputInfo;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.utils.LogUtil;
import com.blockchain.securewallet.tools.SpaceItemDecoration;
import com.blockchain.securewallet.utils.ToastUtils;
import com.blockchain.securewallet.utils.UIHelper;

import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.wallet.DeterministicSeed;
import org.spongycastle.util.encoders.Hex;
import org.web3j.utils.Convert;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.google.common.base.Preconditions.checkArgument;

public class WalletCreateActivity extends BaseActivity {
    private final static String TAG = "Wallet.Create";

    @BindView(R.id.btn_back)
    ImageButton btnBack;

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.btn_next)
    Button btnNext;

    @BindView(R.id.rv_seed_words)
    RecyclerView rvWords;

    @BindView(R.id.tv_change)
    TextView tv_change;

    @BindView(R.id.tv_changeMnemonic)
    TextView tv_changeMnemonic;

    private String password = "pwd@Btc#123";
    private String strCode = "plate magnet happy diary memory speed emerge horn rhythm doctor problem crew";
    private static final String PATH_BITCOIN = "m/44'/0'/0'/0/0";

    private CoinWallet etherWallet = null;
    private CoinWallet bitCoinWallet = null;

    List<String> listMnemonic;

    private WordsAdapter adapter;
    //当前选择是否为英文助记词
    private boolean isEn = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_create);
        ButterKnife.bind(this);

        //Logger.ds("创建钱包");

        tvTitle.setText("创建钱包");

        createSeed(isEn);

        adapter = new WordsAdapter(this, listMnemonic);
        rvWords.setLayoutManager(new GridLayoutManager(this, 3));
        rvWords.addItemDecoration(new SpaceItemDecoration(UIHelper.dipToPx(1.0f)));
        rvWords.setAdapter(adapter);
        ToastUtils.showToast("请将您的密码用手抄或者拍照的方式妥善保管，忘记密码后将无法再找回");

        UIHelper.expandViewTouchDelegate(tv_change, 10, 10, 10, 12);
        UIHelper.expandViewTouchDelegate(tv_changeMnemonic, 10, 10, 10, 4);
    }

    @OnClick(R.id.tv_change)
    void changeSeed() {
        createSeed(isEn);
        adapter.setWords(listMnemonic);
        adapter.notifyDataSetChanged();


//        byte[] seeds= Hex.decode("4c1f97e603e7e1ea0c93886cb7299adb02789246f9aeb1f195c3136ea0e7291b");
//        com.blockchain.securewallet.btc.KeyPair keyPair = BTCUtils.generateWifKey(false, CoinWallet.BIT_COIN_WALLET_TYPE,seeds);
//        ArrayList<UnspentOutputInfo> unspentOutputs = new ArrayList<>();
//        byte[] txHash = BTCUtils.reverse(BTCUtils.fromHex("523312544fd94beeeb4a08127a58cd2f4e412795747759f5ad06216fa85b6d14"));
//        Transaction.Script script = new Transaction.Script(BTCUtils.fromHex("76a914094809350f056628fd9e0011e45253f2033921fc88ac"));
//        long value = 50000;
//        int outputIndex = 0;
//        unspentOutputs.add(new UnspentOutputInfo(keyPair, txHash, script, value, outputIndex));
//        String to = "15jeFJ2LUaUoaZrz8nrqYBkteZZKSrQu2p";
//        String signText = bitCoinWallet.signedBitCoinTransactionData(unspentOutputs,
//                to,bitCoinWallet.getAddress(),10000,50,BTCUtils.TRANSACTION_TYPE_SEGWIT);
//        Log.i("ywLog","signText:"+signText);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (isEn) {
            tv_changeMnemonic.setText(getString(R.string.change_mnemonic_num));
        } else {
            tv_changeMnemonic.setText(getString(R.string.change_mnemonic_en));
        }
    }

    @OnClick(R.id.tv_changeMnemonic)
    void changeMnemonic() {
        isEn = !isEn;

        if (isEn) {
            tv_changeMnemonic.setText(getString(R.string.change_mnemonic_num));
        } else {
            tv_changeMnemonic.setText(getString(R.string.change_mnemonic_en));
        }

        createSeed(isEn);
        adapter.setWords(listMnemonic);
        adapter.notifyDataSetChanged();
    }

    @OnClick(R.id.btn_next)
    void next() {
        Intent intent = new Intent();
        intent.setClass(this, SeedVerifyActivity.class);
        intent.putExtra(SeedVerifyActivity.KEY_WORDS_LIST, strCode);
        startActivity(intent);
//        createBitCoinWallet();
//        signBitcoinTransaction();

    }

    private void createSeed(boolean isEn) {
        int bits = 128;
        byte[] entropy = getEntropy(bits);
        try {
            if (isEn) {
                WalletApp.getInstance().initMnemonicCode(WalletApp.BIP39_WORDLIST_ENGLISH);
            } else {
                WalletApp.getInstance().initMnemonicCode(WalletApp.BIP39_WORDLIST_NUMBER);
            }
            listMnemonic = MnemonicCode.INSTANCE.toMnemonic(entropy);
            StringBuilder builder = new StringBuilder();
            for (String item : listMnemonic) {
                builder.append(item).append(" ");
            }
            strCode = builder.toString().trim();
        } catch (MnemonicException.MnemonicLengthException e) {
            Log.e(TAG, "generate seed failed!", e);
        }
    }


    void transactionSign() {
        signEtherTransaction();
        //signBitcoinTransaction();
    }


    private void signEtherTransaction() {
        String value = "0.001";
        BigInteger realValue = Convert.toWei(value, Convert.Unit.ETHER).toBigInteger();
        String signText = etherWallet.signedEthTransactionData("0x04056831ad7a51ed750631e32b018a49786a0497",
                BigInteger.ZERO,
                new BigInteger("41000000000", 10),
                new BigInteger("21000", 10),
                realValue,
                "0x");
        Log.i(TAG, "signText:" + signText);
        //0xf86b8085098bca5a008252089404056831ad7a51ed750631e32b018a49786a049787038d7ea4c68000801ca081faea92dea059fb8e0c69d03928c2537bdc5e3ec171db4c0eda4514082b14b1a051f3d295f4096ab4be52b180b7c50ad2f655547e9c9a1590dd977b0ac783e8d6
    }


    private void signBitcoinTransaction() {
        byte[] seeds = Hex.decode("4c1f97e603e7e1ea0c93886cb7299adb02789246f9aeb1f195c3136ea0e7291b");
        com.blockchain.securewallet.btc.KeyPair keyPair = BTCUtils.generateWifKey(false, CoinWallet.BIT_COIN_WALLET_TYPE, seeds);
        ArrayList<UnspentOutputInfo> unspentOutputs = new ArrayList<>();
        byte[] txHash = BTCUtils.reverse(BTCUtils.fromHex("523312544fd94beeeb4a08127a58cd2f4e412795747759f5ad06216fa85b6d14"));
        Transaction.Script script = new Transaction.Script(BTCUtils.fromHex("76a914094809350f056628fd9e0011e45253f2033921fc88ac"));
        long value = 50000;
        int outputIndex = 0;
        unspentOutputs.add(new UnspentOutputInfo(keyPair, txHash, script, value, outputIndex));
        String to = "15jeFJ2LUaUoaZrz8nrqYBkteZZKSrQu2p";
        String signText = bitCoinWallet.signedBitCoinTransactionData(unspentOutputs,
                to, bitCoinWallet.getAddress(), 10000, 50, BTCUtils.TRANSACTION_TYPE_SEGWIT);
        Log.i(TAG, "signText:" + signText);

    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }

    private static byte[] getEntropy(int bits) {
        return getEntropy(new SecureRandom(), bits);
    }

    private static byte[] getEntropy(SecureRandom random, int bits) {
        checkArgument(bits <= DeterministicSeed.MAX_SEED_ENTROPY_BITS, "requested entropy size too large");
        //byte[] seed = new byte[]{-19,75,24,112,-98,-70,84,-5,110,118,-25,-49,125,77,96,71};
        byte[] seed = new byte[bits / 8];
        random.nextBytes(seed);
        LogUtil.showInChar(seed, "seed in chars");
        return seed;
    }


}
